package org.example.huweb.web.sys_file.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.Result.Result;
import org.example.Result.ResultUtils;
import org.example.Result.StatusCode;
import org.example.exception.BusinessException;
import org.example.utils.minioUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/api/file")
@RequiredArgsConstructor
public class filesController {

    private final minioUtils minioUtils;

    @RequestMapping("/test")
    public String test() {
        return "test";
    }

    // 删除文件
    @DeleteMapping("/delete/{file}/{fileName}")
    public String deleteFile(@PathVariable String file, @PathVariable String fileName) {
        // TODO : 实现删除文件的逻辑
        return "delete";
    }

    // 上传文件
    // 提供上传文件接口，上传文件到minio服务器
    // 没有业务逻辑，只是上传文件到minio服务器
    @PostMapping("/upload")
    public Result<String> UploadFile(@RequestParam("file") MultipartFile file) {
        String originalFilename;
        try {
            originalFilename = minioUtils.uploadFile(file);
        } catch (Exception e) {
            throw new BusinessException(StatusCode.ERROR_CODE, "文件上传错误");
        }
        return ResultUtils.success(originalFilename);
    }

    // 下载文件
    @RequestMapping("/Download/{file}/{fileName}")
    public ResponseEntity<InputStreamResource> DownloadFile(@PathVariable String file, @PathVariable String fileName) {
        // TODO : 实现下载文件的逻辑但还需要微调业务逻辑

        log.info("访问的文件:{}", file +"/"+ fileName);
        try {
            // 获取文件流
            InputStream inputStream = minioUtils.getFile(file + "/" + fileName);
            // 获取文件类型
            Optional<MediaType> mediaType = MediaTypeFactory.getMediaType(fileName);
            String contentType = mediaType.orElse(MediaType.APPLICATION_OCTET_STREAM).toString();
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, contentType);
            // 返回响应
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new InputStreamResource(inputStream));
        } catch (Exception e) {
            throw new BusinessException(StatusCode.ERROR_CODE, "文件下载错误");
        }

    }


}
